package cn.edu.nchu.controller;

import cn.edu.nchu.entity.CommonResult;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;


@RestController
public class RuleConroller {
    @Autowired
    private RestTemplate restTemplate;
    @Value("${emqx.http-api.rule.url}")
    private String rule_url;

    @GetMapping("/rule/search/{rule_id}")
    public CommonResult<JSONObject> search(@PathVariable String rule_id){
        ResponseEntity<JSONObject> response = restTemplate.exchange(rule_url + "/" + rule_id, HttpMethod.GET, null, JSONObject.class);
        return new CommonResult<> (200, "ok", response.getBody());
    }

    @PostMapping("/rule/create")
    public CommonResult<JSONObject>  create(@RequestBody JSONObject jsonObject){
        ResponseEntity<JSONObject> response = restTemplate.exchange(rule_url, HttpMethod.POST, new HttpEntity<>(jsonObject), JSONObject.class);
        return new CommonResult<> (200, "ok", response.getBody());
    }


    @PutMapping("/rule/update/{rule_id}")
    public CommonResult<JSONObject>  update(@PathVariable("rule_id") String rule_id,
                               @RequestBody JSONObject jsonObject){
        ResponseEntity<JSONObject> response = restTemplate.exchange(rule_url + "/" + rule_id, HttpMethod.PUT,  new HttpEntity<>(jsonObject), JSONObject.class);
        return new CommonResult<> (200, "ok", response.getBody());
    }

    @DeleteMapping("/rule/delete/{rule_id}")
    public CommonResult<JSONObject>  delete(@PathVariable("rule_id") String rule_id){
        ResponseEntity<JSONObject> response = restTemplate.exchange(rule_url + "/" + rule_id, HttpMethod.DELETE, null, JSONObject.class);
        return new CommonResult<> (200, "ok", response.getBody());
    }
}
